package cn.fl.insurance.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;

import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.insurance.condition.InsCompInfoQueryCondition;
import cn.fl.preloan.condition.InsCompChnPolQueryCondition;
import cn.fl.preloan.condition.InsCompInfoQuerysCondition;
import cn.fl.preloan.dto.*;
import cn.fl.preloan.enums.PreloanResultCodeEnum;
import cn.fl.preloan.insurance.IInsCompChnPollService;
import cn.fl.preloan.insurance.IInsCompInfosService;
import cn.fl.upload.constant.UploadConstant;
import com.alibaba.dubbo.config.annotation.Reference;
import cn.fl.commons.result.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.constant.InsuranceConstant;
import cn.fl.insurance.service.IInsCompChnPolService;
import cn.fl.insurance.service.IInsCompInfoService;
import cn.fl.insurance.transform.InsCompChnPolVOTransform;
import cn.fl.insurance.vo.InsCompChnPolVO;
import cn.fl.insurance.vo.InsCompInfoVO;
import cn.fl.project.condition.PrjPrdDtlForInsQueryCondition;
import cn.fl.project.vo.PrjPrdDtlForInsVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.vo.SysUlFilesRecVO;
import net.sf.json.JSONArray;

/**
 * @Description: 保险公司 控制层
 */
@Controller
@RequestMapping("/insurance/insCompInfo")
public class InsCompInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InsCompInfoController.class);

    /**
     *    InsCompInfo 服务层BEAN
     */
    @Autowired
    private IInsCompInfoService insCompInfoService;

    /**
     * 渠道政策 服务层BEAN
     */
    @Autowired
    private IInsCompChnPolService insCompChnPolService;
    @Autowired
    private IInsCompChnPollService insCompChnPollService;
    @Autowired
    private IInsCompInfosService insCompInfosService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载InsCompInfo列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView();
        String compLvl = request.getParameter("compLvl");
        if ("2".equals(compLvl)) {
        	String compPid=request.getParameter("compPid");
        	mav.addObject("compPid", compPid);
        	//保险公司
            GetInsCompInfoListRequest req = new GetInsCompInfoListRequest();
            InsCompInfoQuerysCondition qc = new InsCompInfoQuerysCondition();
            qc.setCompLvl(1);
            req.setCondition(qc);
            ResponseData<InsCompInfoPageResponse> responseData = this.insCompInfosService.selectListByCondition(req);
            List<cn.fl.preloan.dto.InsCompInfoDTO> insCompInfoDTOList = responseData.getData().getInsCompInfoDTOList();
            if (CollectionUtils.isNotEmpty(insCompInfoDTOList)) {
                mav.addObject("insCompList", JSON.toJSONString(insCompInfoDTOList));
            }
            //保险购买方式
            List<KeyValueVO> list=this.insCompInfoService.searchBuyWayCdList();
            mav.addObject("buyWayCdList", JSON.toJSONString(list));
            mav.setViewName("insurance/insCompInfo/insSubCompInfoList");
        } else {
            mav.setViewName("insurance/insCompInfo/insCompInfoList");
        }
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载InsCompInfo Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insCompInfo/insCompInfoModify");
        this.prepare(request, mav);
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载InsCompInfo Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insCompInfo/insCompInfoModify");
        this.prepare(request, mav);
        String id = request.getParameter("id");
        GetByIdRequest req = new GetByIdRequest();
        req.setId(Long.valueOf(id));
        ResponseData data = this.insCompInfosService.selectInsCompInfoById(req);
        InsCompInfoVO insCompInfoVO = new InsCompInfoVO();
        BeanUtils.copyProperties(data.getData(), insCompInfoVO);
        if (insCompInfoVO.getChnBgDt() != null) {
            insCompInfoVO.setChnBgDts(DateUtils.formatDateToString(insCompInfoVO.getChnBgDt(), DateUtils.YYYY_MM_DD));
        }
        if (insCompInfoVO.getChnEndDt() != null) {
            insCompInfoVO.setChnEndDts(DateUtils.formatDateToString(insCompInfoVO.getChnEndDt(), DateUtils.YYYY_MM_DD));
        }
        mav.addObject("insCompInfoVO", insCompInfoVO);
        return mav;
    }

    /**
     * 到修改非我司保险支公司页面
     */
    @RequestMapping(value = "/toModifySubCompPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifySubCompPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifySubCompPage", "加载到修改非我司保险支公司页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView();
        this.prepare(request, mav);
        mav.setViewName("insurance/insCompInfo/insSubCompInfoUpdate");
        String id = request.getParameter("id");
        GetByIdRequest req = new GetByIdRequest();
        req.setId(Long.valueOf(id));
        ResponseData data = this.insCompInfosService.selectInsCompInfoById(req);
        InsCompInfoVO insCompInfoVO = new InsCompInfoVO();
        BeanUtils.copyProperties(data.getData(), insCompInfoVO);
        if (insCompInfoVO.getChnBgDt() != null) {
            insCompInfoVO.setChnBgDts(DateUtils.formatDateToString(insCompInfoVO.getChnBgDt(), DateUtils.YYYY_MM_DD));
        }
        if (insCompInfoVO.getChnEndDt() != null) {
            insCompInfoVO.setChnEndDts(DateUtils.formatDateToString(insCompInfoVO.getChnBgDt(), DateUtils.YYYY_MM_DD));
        }
        mav.addObject("insCompInfoVO", insCompInfoVO);
        return mav;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toCompDtlPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toCompDtlPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载保险(支)公司详情页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insCompInfo/insCompDtlInfo");
        String id = request.getParameter("id");
        InsCompInfoVO insCompInfoVO = this.insCompInfoService.selectById(Long.valueOf(id));
        if (insCompInfoVO.getChnBgDt() != null) {
            insCompInfoVO.setChnBgDts(DateUtils.formatDateToString(insCompInfoVO.getChnBgDt(), DateUtils.YYYY_MM_DD));
        }
        if (insCompInfoVO.getChnEndDt() != null) {
            insCompInfoVO.setChnEndDts(DateUtils.formatDateToString(insCompInfoVO.getChnEndDt(), DateUtils.YYYY_MM_DD));
        }
        if(insCompInfoVO.getCompLvl()==2){//保险支公司
            mav.setViewName("insurance/insCompInfo/insSubCompDtlInfo");
        }
        mav.addObject("insCompInfoVO", insCompInfoVO);
        return mav;
    }

    
    /**
     * 转到新增修改页之前准备数据
     * @param request
     * @param mav
     */
    private void prepare(HttpServletRequest request,ModelAndView mav){
    	//加载数据字典数据、传值等 ？
        String compLvl = request.getParameter("compLvl");
        if (StringUtils.isNotBlank(compLvl) && "2".equals(compLvl)) {
            //保险公司s
            InsCompInfoQuerysCondition qc = new InsCompInfoQuerysCondition();
            qc.setCompLvl(1);
            GetInsCompInfoListRequest req = new GetInsCompInfoListRequest();
            req.setCondition(qc);
            ResponseData<InsCompInfoPageResponse> data = this.insCompInfosService.selectListByCondition(req);
            List<cn.fl.preloan.dto.InsCompInfoDTO> insCompInfoDTOList = data.getData().getInsCompInfoDTOList();
            if (CollectionUtils.isNotEmpty(insCompInfoDTOList)) {
                mav.addObject("insCompList", JSON.toJSONString(insCompInfoDTOList));
            }
            //开户行
            List<KeyValueVO> keyValueVOList=this.insCompInfoService.searchOpenBkInfo();
            mav.addObject("bkIdList", JSON.toJSONString(keyValueVOList));
            //获取渠道
            String chnCd = request.getParameter("chnCd");
            mav.addObject("chnCd",chnCd);
            List<KeyValueVO> list=null;
            if (StringUtils.isNotBlank(chnCd)) {
                KeyValueVO vo=this.insCompInfoService.searchDictListByCd(InsuranceConstant.CODE_INS_COMP_CHN_CD,chnCd);
                if(vo!=null){
                    list = new ArrayList<>();
                    list.add(vo);
                }
            } else {
                list = this.insCompInfoService.searchChnCdList();
            }
            mav.addObject("chnCdList", JSON.toJSONString(list));

            //保险购买方式
            List<KeyValueVO> buyWayCdList=this.insCompInfoService.searchBuyWayCdList();
            mav.addObject("buyWayCdList", JSON.toJSONString(buyWayCdList));
            mav.setViewName("insurance/insCompInfo/insSubCompInfoModify");
        }
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toProcessPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toProcessPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toProcessPage", "加载InsCompInfo ProcessPage页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insCompInfo/insSubCompInfoProcess");
        //加载数据字典数据、传值等 ？
        String id = request.getParameter("id");//保险支公司ID
        String flag = request.getParameter("flag");//标示：0：申请 1.修改 2.查看
        String prInstId=request.getParameter("prInstId");//流程业务主键
        if(StringUtils.isEmpty(id)&&StringUtils.isEmpty(prInstId)){
            return mav;
        }
        BaseLogUtils.newLogger("保险公司管理发起流程开始reqeust:{}",JSON.toJSONString(request.getParameterMap())).info();
        InsCompInfoVO insCompInfoVO = null;
        if(StringUtils.isNotEmpty(id)){
            GetByIdRequest req1 = new GetByIdRequest();
            req1.setId(Long.valueOf(id));
            ResponseData data1= this.insCompInfosService.selectInsCompInfoById(req1);
            BaseLogUtils.newLogger("查询保险公司接口结束:data:{}",JSON.toJSONString(data1)).info();
            if(null != data1.getData()) {
                insCompInfoVO = new InsCompInfoVO();
                BeanUtils.copyProperties(data1.getData(), insCompInfoVO);
            }
        }
        if(StringUtils.isNotEmpty(prInstId)){
            InsCompChnPolQueryCondition condition=new InsCompChnPolQueryCondition();
            condition.setPrInstId(prInstId);
            GetInsCompChnPolListRequest req = new GetInsCompChnPolListRequest();
            req.setCondition(condition);
            List<InsCompChnPolVO> insCompChnPolVOList = new ArrayList<>();
            BaseLogUtils.newLogger("查询保险公司渠道政策接口开始condition:{}",JSON.toJSONString(condition)).info();
            ResponseData<InsCompChnPolResponse> data =this.insCompChnPollService.selectListByCondition(req);
            BaseLogUtils.newLogger("查询保险公司渠道政策接口结束data:{}",JSON.toJSONString(data)).info();
            List<InsCompChnPolDTO> insCompChnPolDTOList = data.getData().getInsCompChnPolDTOList();
            if(CollectionUtils.isNotEmpty(insCompChnPolDTOList)){
                if(insCompInfoVO==null){
                    GetByIdRequest req2 = new GetByIdRequest();
                    Long compId=insCompChnPolDTOList.get(0).getInsCompId();
                    req2.setId(compId);
                    BaseLogUtils.newLogger("根据id查询查询保险公司详情开始req2:{}",JSON.toJSONString(req2)).info();
                    ResponseData data1= this.insCompInfosService.selectInsCompInfoById(req2);
                    BaseLogUtils.newLogger("根据id查询查询保险公司详情结束data1:{}",JSON.toJSONString(data1)).info();
                    if(null != data1.getData()) {
                        insCompInfoVO = new InsCompInfoVO();
                        BeanUtils.copyProperties(data1.getData(), insCompInfoVO);
                    }
                }
                for(InsCompChnPolDTO insCompChnPolDTO :insCompChnPolDTOList){
                    InsCompChnPolVO ins = new InsCompChnPolVO();
                    BeanUtils.copyProperties(insCompChnPolDTO, ins);
                    insCompChnPolVOList.add(ins);
                }
                for(InsCompChnPolVO vo:insCompChnPolVOList){
                   vo.setRebAmtDou(DecimalUtils.convertFenToYuan(vo.getRebAmt()));
                }
                mav.addObject("chnPolList",JSON.toJSONString(insCompChnPolVOList));
            }
        }

        if(insCompInfoVO!=null){
            BaseLogUtils.newLogger("查询保险购买方式开始buyWayCd:{}",insCompInfoVO.getBuyWayCd()).info();
            KeyValueVO keyValueVO=this.insCompInfoService.searchDictListByCd(InsuranceConstant.CODE_INS_BUY_WAY_CD,insCompInfoVO.getBuyWayCd());
            BaseLogUtils.newLogger("查询保险购买方式结束buyWayCd:{},keyValueVO:{}",insCompInfoVO.getBuyWayCd(),JSON.toJSONString(keyValueVO)).info();
            insCompInfoVO.setBuyWayCdNm(keyValueVO.getValue());
            BaseLogUtils.newLogger("查询保险公司渠道开始buyWayCd:{}",insCompInfoVO.getChnCd()).info();
            keyValueVO=this.insCompInfoService.searchDictListByCd(InsuranceConstant.CODE_INS_COMP_CHN_CD,insCompInfoVO.getChnCd());
            BaseLogUtils.newLogger("查询保险公司渠道结束buyWayCd:{},keyValueVO:{}",insCompInfoVO.getChnCd(),JSON.toJSONString(keyValueVO)).info();
            insCompInfoVO.setChnCdNm(keyValueVO.getValue());
        }
        mav.addObject("insCompInfoVO", insCompInfoVO);

        mav.addObject("flag",flag);
        mav.addObject("prInstId",prInstId);//流程业务主键
        BaseLogUtils.newLogger("保险公司发起流程页面组装结束:mavv:{}",JSON.toJSONString(mav)).info();
        return mav;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initInsCompInfoList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(currentPage)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        InsCompInfoQuerysCondition qc = new InsCompInfoQuerysCondition();
        //设置查询条件？
        String compLvl = request.getParameter("compLvl");//保险公司层级
        String compPid = request.getParameter("compPid");//保险公司父ID
        String compPidNm = request.getParameter("compPidNm");//保险公司名称
        String compNm = request.getParameter("compNm");//保险公司
        String chnCd = request.getParameter("chnCd");//渠道
        String buyWayCd = request.getParameter("buyWayCd");//购买方式
        String rgnPrCd = request.getParameter("rgnPrCd");//支公司所属地
        if (StringUtils.isNotEmpty(compLvl)) {
            qc.setCompLvl(Integer.valueOf(compLvl));
        }
        if (StringUtils.isNotEmpty(compPid)) {
            qc.setCompPid(Long.valueOf(compPid));
        }
        if (StringUtils.isNotEmpty(compPidNm)) {
            qc.setCompPidNm(compPidNm);
        }
        if (StringUtils.isNotEmpty(compNm)) {
            qc.setCompNm(compNm);
        }
        if (StringUtils.isNotBlank(chnCd)) {
            qc.setChnCd(chnCd);
        }
        if(StringUtils.isNotBlank(buyWayCd)){
            qc.setBuyWayCd(buyWayCd);
        }
        if(StringUtils.isNotBlank(rgnPrCd)){
            qc.setRgnPrCd(rgnPrCd);
        }
        qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        qc.setUsrId(CurrentThreadContext.getCurrentUserId());
        page.setCondition(qc);
        List<InsCompInfoVO> insCompInfoVOList = new ArrayList<>();
        BaseLogUtils.info(logger, "initInsCompInfoList", "初始化InsCompInfo列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        ResponseData<InsCompInfoPageResponse> data = insCompInfosService.searchListPageByCondition(page.getCurrentPage(), page.getEveryPage(), qc);
        List<cn.fl.preloan.dto.InsCompInfoDTO> insCompInfoDTOList = data.getData().getInsCompInfoDTOList();
        for(cn.fl.preloan.dto.InsCompInfoDTO insCompInfoDTO :insCompInfoDTOList){
            InsCompInfoVO ins = new InsCompInfoVO();
            BeanUtils.copyProperties(insCompInfoDTO, ins);
            insCompInfoVOList.add(ins);
        }
        ListPageVO<InsCompInfoVO> listPage = new ListPageVO<InsCompInfoVO>(insCompInfoVOList, data.getData().getTotalCount());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeInsCompInfoByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeInsCompInfoByIds", "删除InsCompInfo数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            DeleteCompInfoById req = new DeleteCompInfoById();
            req.setIds(idsList);
            req.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            ResponseData data = insCompInfosService.deleteByIds(req);
            if (!data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeInsCompInfoByIds", "删除InsCompInfo数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeInsCompInfoByIds", "删除InsCompInfo数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeInsCompInfoByIds", "删除InsCompInfo数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeInsCompInfoByIds", "删除InsCompInfo数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getInsCompInfoById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getInsCompInfoById", "获取InsCompInfo数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {

            GetByIdRequest req = new GetByIdRequest();
            req.setId(Long.valueOf(id));
            ResponseData data = insCompInfosService.selectInsCompInfoById(req);
            InsCompInfoVO vo = new InsCompInfoVO();
            BeanUtils.copyProperties(data.getData(),vo);
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getInsCompInfoById", "获取InsCompInfo数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getInsCompInfoById", "获取InsCompInfo数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getInsCompInfoById", "获取InsCompInfo数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getInsCompInfoById", "获取InsCompInfo数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addInsCompInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        InsCompInfoVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForInsCompInfo(request);//获取参数
            Long id  = insCompInfoService.add(entity);
            BaseLogUtils.info(logger, "addInsCompInfo", "新增InsCompInfo数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addInsCompInfo", "新增InsCompInfo数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addInsCompInfo", "新增InsCompInfo数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyInsCompInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        InsCompInfoVO entity = null;
        try {
            entity = this.getRequestParamForInsCompInfo(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyInsCompInfo", "修改InsCompInfo信息,主键参数为空！.ID:" + entity.getId(), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            boolean success = insCompInfoService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyInsCompInfo", "修改InsCompInfo数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyInsCompInfo", "修改InsCompInfo数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyInsCompInfo", "修改InsCompInfo数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyInsCompInfo", "修改InsCompInfo数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 查询保险支公司列表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/selectInsSubComp.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object selectInsSubComp(HttpServletRequest request, HttpServletResponse response){
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        List<InsCompInfoVO> list=new ArrayList<>();
        InsCompInfoQueryCondition qc = new InsCompInfoQueryCondition();
        qc.setCompLvl(2);
        String insCompId=request.getParameter("insCompId");
        if(StringUtils.isNotBlank(insCompId)){
            qc.setCompPid(Long.valueOf(insCompId));
        }
        String prCd=request.getParameter("rgnPrCd");
        if(StringUtils.isNotBlank(prCd)){
            qc.setRgnPrCd(prCd);
        }
        String cyCd=request.getParameter("rgnCyCd");
        if(StringUtils.isNotBlank(cyCd)){
            qc.setRgnCyCd(cyCd);
        }
        String buyWayCd=request.getParameter("buyWayCd");
        if(StringUtils.isNotBlank(buyWayCd)){
            qc.setBuyWayCd(buyWayCd);
        }
        qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        String paySchNo=request.getParameter("paySchNo");
        if(StringUtils.isNotBlank(paySchNo)){
           qc.setPaySchNo(paySchNo.trim());
        }
        String prjPrdDtlId=request.getParameter("prjPrdDtlId");
        if(StringUtils.isNotEmpty(prjPrdDtlId)){
            qc.setPrjPrdDtlId(Long.parseLong(prjPrdDtlId));
        }
        String plcSpePolCd=request.getParameter("plcSpePolCd");
        if(StringUtils.isNotEmpty(plcSpePolCd)){
            qc.setPlcSpePolCd(plcSpePolCd);
        }
        String insTypCd=request.getParameter("insTypCd");
        if(StringUtils.isNotEmpty(insTypCd)){
            qc.setInsTypCd(insTypCd);
        }
        String prdTypCd=request.getParameter("prdTypCd");
        if(StringUtils.isNotBlank(prdTypCd)){
            qc.setPrdTypCd(prdTypCd);
        }
        BaseLogUtils.info(logger,"selectInsSubComp","查询保险支公司===");
        Map<String,Object> map=this.insCompInfoService.selectInsSubComp(qc);
        if(CollectionUtils.isMapEmpty(map)){
            BaseLogUtils.info(logger,"selectInsSubComp","查询保险支公司===>未找到可用的保险支公司");
        }else{
            result.setData(map);
            BaseLogUtils.info(logger,"selectInsSubComp","查询到保险支公司===>渠道政策"+map.get("chnPol"));
        }
        return result;
    }

    /**
     * 查询客户经理名下未投保的支付表产品信息 -非我司渠道保险支公司
     */
    @RequestMapping(value = "/selectPrjPrdList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object selectPrjPrdList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        PrjPrdDtlForInsQueryCondition qc = new PrjPrdDtlForInsQueryCondition();
        qc.setCstMgrId(CurrentThreadContext.getCurrentUserId());
        //qc.setInsStsCd(InsuranceConstant.CODE_INS_PRD_STS_CD_10);

        String condition=request.getParameter("condition");
        if(StringUtils.isNotBlank(condition)){
            JSONArray conditionArray = JSONArray.fromObject(condition);
            for (Object object : conditionArray) {
                net.sf.json.JSONObject jsonObject=(net.sf.json.JSONObject)object;
                if("paySchNo".equals(String.valueOf(jsonObject.get("field")))){
                    qc.setPaySchNo(String.valueOf(jsonObject.get("value")));
                }
                if("cstNm".equals(String.valueOf(jsonObject.get("field")))){
                    qc.setCstNm(String.valueOf(jsonObject.get("value")));
                }
            }
        }
        page.setCondition(qc);

        //设置查询条件？
        BaseLogUtils.info(logger, "selectPrjPrdList", "查询客户经理名下支付表产品信息.DATA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.insCompInfoService.selectPrjPrdListPage(page);
        List<PrjPrdDtlForInsVO> list = (List<PrjPrdDtlForInsVO>) pager.getResultList();
        ListPageVO<PrjPrdDtlForInsVO> listPage = new ListPageVO<PrjPrdDtlForInsVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private InsCompInfoVO getRequestParamForInsCompInfo(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String compNm = request.getParameter("compNm");
        String compNo = request.getParameter("compNo");
        String compPid = request.getParameter("compPid");
        String compLvl = request.getParameter("compLvl");
        String compStsCd = request.getParameter("compStsCd");
        String compAddr = request.getParameter("compAddr");
        String lmNm = request.getParameter("lmNm");
        String lmTel = request.getParameter("lmTel");
        String lmEmail = request.getParameter("lmEmail");
        String faxNo = request.getParameter("faxNo");
        String zipNo = request.getParameter("zipNo");
        String bkId = request.getParameter("bkId");
        String bkNm = request.getParameter("bkNm");
        String bkNo = request.getParameter("bkNo");
        String accNm = request.getParameter("accNm");
        String accNo = request.getParameter("accNo");
        String compRem = request.getParameter("compRem");
        String buyWayCd = request.getParameter("buyWayCd");
        String rgnCyCd = request.getParameter("rgnCyCd");
        String rgnPrCd = request.getParameter("rgnPrCd");
        String chnCd = request.getParameter("chnCd");
        String chnBgDt = request.getParameter("chnBgDt");
        String chnEndDt = request.getParameter("chnEndDt");
        String protNo = request.getParameter("protNo");
        String rgnCyNm = request.getParameter("rgnCyNm");
        String rgnPrNm = request.getParameter("rgnPrNm");
        String fileParams = request.getParameter("fileParams");//附件上传信息

        /*String orgCd = request.getParameter("orgCd");*/

        //验证参数并赋值
        InsCompInfoVO entity = new InsCompInfoVO();
        if (StringUtils.isBlank(compNm)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "保险公司名称不能为空.");
        }
        entity.setCompNm(compNm.trim());
        entity.setCompNo(compNo);
        entity.setLmEmail(lmEmail);
        entity.setZipNo(zipNo);
        entity.setCompAddr(compAddr);
        entity.setCompRem(compRem);
        entity.setBkNm(bkNm);
        entity.setFaxNo(faxNo);
        entity.setProtNo(protNo);

        if (StringUtils.isNotBlank(chnCd)) {
            if (StringUtils.isBlank(buyWayCd.trim())) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "购买方式不能为空.");
            }
            entity.setBuyWayCd(buyWayCd);
            entity.setChnCd(chnCd);
            entity.setRgnCyCd(rgnCyCd);
            entity.setRgnPrCd(rgnPrCd);
            entity.setRgnCyNm(rgnCyNm);
            entity.setRgnPrNm(rgnPrNm);

            //if ("1".equals(chnCd.trim())) {
                if (StringUtils.isBlank(lmNm)) {
                    throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "联系人不能为空.");
                }
                if (StringUtils.isBlank(lmTel)) {
                    throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "联系电话不能为空.");
                }
                if (StringUtils.isBlank(bkId)) {
                    throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "开户行不能为空.");
                }
                if (StringUtils.isBlank(bkNo)) {
                    throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "开户行号不能为空.");
                }
                if (StringUtils.isBlank(accNm)) {
                    throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "账户名称不能为空.");
                }
                if (StringUtils.isBlank(accNo)) {
                    throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "银行账号不能为空.");
                }
                entity.setBkId(bkId);
                entity.setBkNo(bkNo);
                entity.setAccNm(accNm);
                entity.setAccNo(accNo);
                entity.setChnBgDt(DateUtils.formatStringToDate(chnBgDt, DateUtils.YYYY_MM_DD));
                entity.setChnEndDt(DateUtils.formatStringToDate(chnEndDt, DateUtils.YYYY_MM_DD));
            //}

            //解析附件上传信息
            if (StringUtils.isNotBlank(fileParams)) {
                List<Map<String, String>> fileParamsList = new ArrayList<Map<String, String>>();
                JSONArray arry = JSONArray.fromObject(fileParams);
                for (int i = 0; i < arry.size(); i++) {
                    net.sf.json.JSONObject jsonObject = arry.getJSONObject(i);
                    Iterator<?> it = jsonObject.keys();
                    HashMap<String, String> hMap = new HashMap<String, String>();
                    while (it.hasNext()) {
                        String key = String.valueOf(it.next());
                        String value = (String) jsonObject.get(key);
                        hMap.put(key, value);
                    }
                    fileParamsList.add(hMap);
                }
                List<SysUlFilesRecVO> sysUlFilesRecVOList = new ArrayList<SysUlFilesRecVO>();
                for (Map<String, String> map : fileParamsList) {
                    SysUlFilesRecVO sysUlFilesRecVO = new SysUlFilesRecVO();
                    sysUlFilesRecVO.setFileNm(map.get("fileNm"));
                    sysUlFilesRecVO.setFilePath(map.get("filePath"));
                    sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH)+map.get("filePath"));
                    sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
                    sysUlFilesRecVO.setOrgCd("0000");
                    sysUlFilesRecVO.setCfgCd(InsuranceConstant.CODE_INS_COMP_CFG_CD);
                    sysUlFilesRecVO.setCfgDtlCd(InsuranceConstant.CODE_INS_COMP_CFG_DTL_CD);
                    sysUlFilesRecVOList.add(sysUlFilesRecVO);
                }
                entity.setSysUlFilesRecVOList(sysUlFilesRecVOList);
            }

        }
        if (StringUtils.isNotBlank(lmNm)) {
            entity.setLmNm(lmNm.trim());
        }
        if (StringUtils.isNotBlank(lmTel)) {
            entity.setLmTel(lmTel.trim());
        }
        if (StringUtils.isNotBlank(compLvl)) {
            entity.setCompLvl(Integer.valueOf(compLvl));
        }
        if (StringUtils.isNotBlank(compPid)) {
            entity.setCompPid(Long.valueOf(compPid));
        }
        if (StringUtils.isNotBlank(compStsCd)) {
            entity.setCompStsCd(compStsCd);
        }

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        }else{
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());
            entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
        }

        return entity;
    }
}

